﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Modules.Membership.ModelBinders
{
    public class UserGroupInputModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            //Guid parentID = !String.IsNullOrEmpty(valueProvider.GetAttemptedValue("parentID"]) ? new Guid(valueProvider.GetAttemptedValue("parentID"]) : Guid.Empty;
            Guid tmpGuid;
            Guid? userGroupID = null;
            if (valueProvider.GetAttemptedValue("userGroupID").GuidTryParse(out tmpGuid))
                userGroupID = tmpGuid;
            Guid? parentID = null;
            if (valueProvider.GetAttemptedValue("parentID").GuidTryParse(out tmpGuid))
                parentID = tmpGuid;

            string userGroupName = valueProvider.GetAttemptedValue("userGroupName");

            IEnumerable<Guid> roleIDList = Enumerable.Empty<Guid>();
            if (!String.IsNullOrEmpty(valueProvider.GetAttemptedValue("Roles")))
            {
                string[] permissionArray = valueProvider.GetAttemptedValue("Roles").Split(',');

                roleIDList = from s in permissionArray
                             where s.IsGuid()
                             select new Guid(s);
            }

            return new UserGroupInput
            {
                ParentID = parentID,
                UserGroupID = userGroupID,
                UserGroupName = userGroupName,
                Roles = roleIDList
            };            
        }
    }
}
